package ua.kpi.fpm.km61.strat.sp.la.utils;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import ua.kpi.fpm.km61.strat.sp.la.MarkedString;

public class PreProcessor {

    public static List<MarkedString> buildText(File inpFile) {
	List<MarkedString> text = new ArrayList<MarkedString>();
	if (inpFile != null) {

	    try {
		FileReader fr = new FileReader(inpFile);
		BufferedReader br = new BufferedReader(fr);
		text.addAll(PreProcessor.splite(br));
		br.close();
		fr.close();
	    } catch (IOException e) {
		e.printStackTrace();
	    }
	}
	return text;
    }

    private static List<MarkedString> splite(BufferedReader br)
	    throws IOException {
	List<MarkedString> text = new ArrayList<MarkedString>();
	if (br != null) {
	    String tmp = "";
	    int i = 1;
	    while ((tmp = br.readLine()) != null) {
		MarkedString fw = new MarkedString(i, 0, tmp);
		text.add(fw);
		i++;
	    }
	}
	return text;
    }

    public static List<MarkedString> delLineComments(List<MarkedString> inpText) {
	if (inpText == null) {
	    return new ArrayList<MarkedString>();
	}
	int k = 0;
	while (k < inpText.size()) {
	    MarkedString m = inpText.get(k);
	    String tmp = m.getStr();
	    if ((tmp.startsWith("//"))) {
		inpText.remove(k);
		break;
	    }
	    tmp = tmp.indexOf("//") > 0 ? tmp.substring(0, tmp.indexOf("//"))
		    : tmp;
	    m.setStr(tmp);
	    k++;
	}
	return inpText;
    }

    public List<MarkedString> delBlockComments(List<MarkedString> lm) {
	int k = 0;
	while (k < lm.size()) {
	    MarkedString m = lm.get(k);
	    String tmp = m.getStr();
	    if (PreProcessor.stringHasBlockCommentEnding(tmp)) {
		return new ArrayList<MarkedString>();
	    }
	    if (tmp.indexOf("/*") >= 0) {
		tmp = tmp.substring(0, tmp.indexOf("/*"));
		m.setStr(tmp);
		int i = k + 1;
		while (i < lm.size()) {
		    MarkedString m1 = lm.get(i);
		    String tmp1 = m1.getStr();
		    if (PreProcessor.stringHasBlockCommentEnding(tmp1)) {
			tmp1 = PreProcessor.delBlockCommentedPart(tmp1);
			m1.setStr(tmp1);
			i++;
			break;
		    }
		    lm.remove(i);
		}
		m.setStr(tmp);
	    }
	    k++;
	}
	return lm;
    }

    private static boolean stringHasBlockCommentEnding(String tmp) {
	return tmp.indexOf("*/") >= 0;
    }

    private static String delBlockCommentedPart(String str) {
	if (str == null) {
	    return str;
	}
	str = str
		.substring(str.lastIndexOf("*/") + "*/".length(), str.length());
	return str;
    }
}
